package com.github.lanif.core.config;

import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 0
 * @date 2020/11/2 19:04
 * @description
 */
@Configuration
public class RestTemplateConfig {

    /**
     * spring 默认简单工厂
     * @return
     */
    @Bean("simple")
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }

    /**
     * httpclient 工厂可以处理压缩的gzip text/json
     * 解决：JsonParseException: Illegal character ((CTRL-CHAR, code 31))
     * @return
     */
    @Bean("advanced")
    public ClientHttpRequestFactory advancedClientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory =
                new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build());

        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }

    @Bean
    public RestTemplate restTemplate(@Qualifier("simple") ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean("advancedRestTemplate")
    public RestTemplate laxRestTemplate(@Qualifier("advanced") ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        List<MediaType> mediaTypes = new ArrayList<>();
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        mediaTypes.add(MediaType.TEXT_HTML);
        mediaTypes.add(MediaType.TEXT_PLAIN);
        mediaTypes.add(MediaType.APPLICATION_JSON);
        mediaTypes.add(MediaType.valueOf("text/json;charset=UTF-8"));
        converter.setSupportedMediaTypes(mediaTypes);
        restTemplate.getMessageConverters().add(converter);
        return restTemplate;
    }

}